export function arraysEqual(arr1, arr2) {
	// 首先检查数组长度是否相等
	if (arr1.length !== arr2.length) {
		return false;
	}
	// 然后逐个比较数组元素
	for (let i = 0; i < arr1.length; i++) {
		if (arr1[i] !== arr2[i]) {
			return false;
		}
	}
	// 如果循环结束后没有发现不相等的元素，那么数组相等
	return true;
}
// 格式化价格（去掉末尾0）
export function countSum(arr = []) {
	if (!(arr instanceof Array)) {
		arr = [arr]
	}

	if (!arr.length) return 0;
	arr = arr.map((v) => {
		if (v && !Number.isNaN(Number(v))) return Math.round(v * 100);
		return 0;
	});
	const result = arr.reduce((prev, curr) => {
		return prev + curr
	}, 0);
	return result / 100;
}


//格式化价格
export function parseFloat(num) {
	return Number(num).toFixed(2);
}


/**
 * 请求函数
 * data:数据
 * url:链接地址
 * isBaseUrl:是否公共接口，
 * showLoading: 显示loading
 */

export function svg(str) {
	return 'data:image/svg+xml;base64,' + Buffer.from(str).toString('base64');
}




export function $request(url, data, method, contentType,originateenum) {
	return new Promise((resolve, reject) => {
		// 注意：这里的代码仍然是异步的，但我们使用了Promise和async/await来简化调用
		(async () => {
			try {
				let usrUserId = uni.getStorageSync('usrUserId')
				let openid = uni.getStorageSync('openId')
				let lgToken = uni.getStorageSync('lgToken')
				let content = contentType ? contentType : 'application/json'
				let originat = originateenum ? originateenum : ''
				let header = {}
				if (originat) {
					header = {
						'originateenum': originat,
						'content-type': content,
						'usruserid': usrUserId,
						'openid': openid,
						'hspid': 23840,
						'lgToken': lgToken,
					}
					}else {
						header = {
							'content-type': content,
							'usruserid': usrUserId,
							'openid': openid,
							'hspid': 23840,
							'lgToken': lgToken,
						}
					}
				let rs = await uni.request({
					url: 'https://app.mzmzb.com/application-usrapp/' + url,
					data: data,
					method: method,
					header: header
				});
				resolve(rs[1]); // 当请求成功时解析Promise
			} catch (error) {
				reject(error); // 当请求失败时拒绝Promise
			}
		})();
	});
}


//数据是否为空[string,array,object]
export function isNull(param) {
	//字符串
	if (
		!param ||
		param == undefined ||
		param == null ||
		param == "" ||
		param.trim() == ""
	) {
		return false;
	}
	//数组
	if (Array.isArray(param) && param.length == 0) {
		return false;
	}
	//对象
	if (JSON.stringify(data) == "{}") {
		return false;
	}
	return true;
}

// 截断
export function truncate(str, length = '') {
	if (!length) {
		length = str.length
	}
	let len = 0;
	let result = '';
	for (let i = 0; i < str.length; i++) {
		if (str.charCodeAt(i) > 127 || str.charCodeAt(i) == 94) {
			len += 2;
		} else {
			len++;
		}
		if (len > length) {
			break;
		}
		result += str.charAt(i);
	}
	if (str.length > length) {
		result += "..."
	}

	return result
}

//显示提示
export function showToast(title) {
	uni.showToast({
		title,
		icon: "none",
		duration: 2000,
	});
}

//分隔回车和逗号函数
export function explode(rule = /[\n,]/g, str) {
	var temp = str.split(rule);
	for (var i = 0; i < temp.length; i++) {
		if (temp[i] == "") {
			temp.splice(i, 1);
			i--;
		}
	}
	return temp;
}
//操作成功后提示后跳转
export function success(msg = "操作成功！", path = "", seconds = 1.5) {
	msg = msg + ''
	const time = 1000;
	uni.showToast({
		icon: "success",
		title: msg,
		duration: seconds * time,
	});
	if (path) {
		setTimeout(() => {
			goto(path);
		}, seconds * time);
	}
}
//错误提示跳转
export function error(msg = "", path = "", seconds = 1.5) {
	msg = msg + ''
	const time = 1000;
	uni.showToast({
		icon: "none",
		title: msg,
		duration: seconds * time,
	});
	if (path) {
		setTimeout(() => {
			goto(path);
		}, seconds * time);
	}
	return false;
}
/**
 * 数组查找
 * @param  {[type]} search [description]
 * @param  {[type]} array  [description]
 * @return {[type]}        [description]
 */
export function in_array(search, array) {
	for (var i in array) {
		if (array[i] == search) {
			return true;
		}
	}
	return false;
}

//对象转数组
export function toArray(data) {
	let arr = [];
	for (var i in data) {
		arr.push(data[i]);
	}
	return arr;
}

// 复制
export function copy(text) {
	//#ifdef H5
	var oInput = document.createElement('input');
	oInput.value = text;
	document.body.appendChild(oInput);
	oInput.select();
	document.execCommand("Copy");
	oInput.className = 'oInput';
	oInput.style.display = 'none';
	success('复制成功');
	//#endif

	//#ifdef MP-WEIXIN
	uni.setClipboardData({
		data: text
	});
	uni.getClipboardData();
	success('复制成功');
	//#endif
}

/**
 * This is just a simple version of deep copy
 * Has a lot of edge cases bug
 * If you want to use a perfect deep copy, use lodash's _.cloneDeep
 * @param {Object} source
 * @returns {Object}
 */
//格式化价格
/**
 * @description 模仿PHP的strtotime()函数
 * strtotime('2012-07-27 12:43:43') OR strtotime('2012-07-27')
 * @return 时间戳
 */
export function strtotime(str) {
	var _arr = str.split(' ');
	var _day = _arr[0].split('-');
	_arr[1] = (_arr[1] == null) ? '0:0:0' : _arr[1];
	var _time = _arr[1].split(':');
	for (var i = _day.length - 1; i >= 0; i--) {
		_day[i] = isNaN(parseInt(_day[i])) ? 0 : parseInt(_day[i]);
	}
	for (var i = _time.length - 1; i >= 0; i--) {
		_time[i] = isNaN(parseInt(_time[i])) ? 0 : parseInt(_time[i]);
	}
	var _temp = new Date(_day[0], _day[1] - 1, _day[2], _time[0], _time[1], _time[2]);
	return _temp.getTime() / 1000;
}

export function toNumber(str = '') {
	if (str === '') {
		return '';
	}
	return Number(str)
}

/**
 * 格式化时间
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string}
 */
export function parseTime(time, cFormat) {
	time = parseInt(time)
	if (time == 0) return "";
	if (arguments.length === 0) {
		return null;
	}
	const format = cFormat || "{y}-{m}-{d} {h}:{i}";
	let date;
	if (typeof time === "object") {
		date = time;
	} else {
		if (typeof time === "string" && /^[0-9]+$/.test(time)) {
			time = parseInt(time);
		}
		if (typeof time === "number" && time.toString().length < 11) {
			time = time * 1000;
		}
		date = new Date(time);
	}
	const formatObj = {
		y: date.getFullYear(),
		m: date.getMonth() + 1,
		d: date.getDate(),
		h: date.getHours(),
		i: date.getMinutes(),
		s: date.getSeconds(),
		a: date.getDay(),
	};
	const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
		let value = formatObj[key];
		// Note: getDay() returns 0 on Sunday
		if (key === "a") {
			return ["日", "一", "二", "三", "四", "五", "六"][value];
		}
		if (result.length > 0 && value < 10) {
			value = "0" + value;
		}
		return value || 0;
	});
	return time_str;
}

export function parseTime1(time, cFormat) {
	time = parseInt(time)
	if (time == 0) return "";
	if (arguments.length === 0) {
		return null;
	}
	const format = cFormat || "{y}/{m}/{d}";
	let date;
	if (typeof time === "object") {
		date = time;
	} else {
		if (typeof time === "string" && /^[0-9]+$/.test(time)) {
			time = parseInt(time);
		}
		if (typeof time === "number" && time.toString().length < 11) {
			time = time * 1000;
		}
		date = new Date(time);
	}
	const formatObj = {
		y: date.getFullYear(),
		m: date.getMonth() + 1,
		d: date.getDate(),
		h: date.getHours(),
		i: date.getMinutes(),
		s: date.getSeconds(),
		a: date.getDay(),
	};
	const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
		let value = formatObj[key];
		// Note: getDay() returns 0 on Sunday
		if (key === "a") {
			return ["日", "一", "二", "三", "四", "五", "六"][value];
		}
		if (result.length > 0 && value < 10) {
			value = "0" + value;
		}
		return value || 0;
	});
	return time_str;
}

//是否是数组
export function isArray(o) {
	return Object.prototype.toString.call(o) == '[object Array]';
}



//删除子数组
export function deleteChildren(arr) {
	arr = arr.slice();

	function toParse(arr) {
		arr.forEach(function(item, index, array) {
			if (
				item.children &&
				Array.isArray(item.children) &&
				item.children.length > 0
			) {
				toParse(item.children);
			} else {
				delete item.children;
			}
		});
		return arr;
	}
	return toParse(arr);
}

//数组去重
export function uniqueArr(arr) {
	return Array.from(new Set(arr));
}
//打电话
export function phoneCall(phoneNumber) {
	uni.makePhoneCall({
		phoneNumber: phoneNumber,
	});
}
//显示图片
export function showPic(pics, index) {
	uni.previewImage({
		current: index,
		urls: pics
	})
}
// 下划线转换驼峰
export function toHump(name) {
	return name.replace(/\_(\w)/g, function(all, letter) {
		return letter.toUpperCase();
	});
}
// 驼峰转换下划线
export function toLine(name) {
	return name.replace(/([A-Z])/g, "_$1").toLowerCase();
}
// 手机号隐藏4位
export function geTel(tel) {
	var reg = /^(\d{3})\d{4}(\d{4})$/;
	return tel.replace(reg, "$1****$2");
}
// 银行卡号码格式显示带*号（**** **** **** 1234）
export function bankVerification(data) {
	return data.replace(/\s/g, '').replace(/(\d{4})\d+(\d{4})$/, "**** **** **** $2");
}